<template>
  <div class="space-y-4">
    <n-card :bordered="false" size="small">
      <div class="flex justify-between items-center">
        <n-space align="center" wrap>
          <n-input
            v-model:value="searchKeyword"
            placeholder="搜索党员姓名或手机号"
            clearable
            style="width: 240px"
          >
            <template #prefix><n-icon :component="SearchIcon" /></template>
          </n-input>
          
          <n-select
            v-model:value="selectedGender"
            placeholder="按性别筛选"
            :options="genderOptions"
            clearable
            style="width: 140px"
          />
          <n-select
            v-model:value="selectedStatus"
            placeholder="按政治面貌筛选"
            :options="statusOptions"
            clearable
            style="width: 160px"
          />
          <n-select
            v-model:value="selectedClass"
            placeholder="按班级筛选"
            :options="classOptions"
            filterable
            clearable
            style="width: 200px"
          />
          <n-select
            v-model:value="selectedGraduationStatus"
            placeholder="按毕业状态筛选"
            :options="graduationStatusOptions"
            clearable
            style="width: 140px"
          />
          
          <n-date-picker
            v-model:formatted-value="selectedDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="查询特定日期的成员名单"
            clearable
            style="width: 200px"
            @update:value="handleDateChange"
          />
          
          <n-tag type="info">
              当前: {{ filteredMembers.length }} 人
          </n-tag>
          
          <n-button
            size="small"
            @click="clearAllFilters"
            :disabled="!hasActiveFilters"
          >
            清除筛选
          </n-button>
        </n-space>
        
        <n-button
          type="primary"
          :disabled="checkedRowKeys.length === 0"
          @click="showTransferModal = true"
        >
          <template #icon><n-icon :component="TransferIcon" /></template>
          转移选中成员 ({{ checkedRowKeys.length }})
        </n-button>
      </div>
    </n-card>

    <!-- 日期查询结果说明 -->
    <n-card v-if="selectedDate" size="small" :bordered="false" class="date-query-card">
      <div class="flex items-center justify-between">
        <span class="text-sm text-gray-600">
          查询日期：{{ formatDate(selectedDate) }} 的党支部成员名单
        </span>
        <n-tag type="info" size="small">
          {{ isHistoricalQuery ? '历史查询' : '当前成员' }}
        </n-tag>
      </div>
    </n-card>

    <n-card :bordered="false">
      <n-data-table
        :columns="columns"
        :data="filteredMembers"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
        :row-key="row => row.memberId"
        v-model:checked-row-keys="checkedRowKeys"
      />
    </n-card>

    <n-modal
      v-model:show="showTransferModal"
      preset="dialog"
      title="组织关系转移"
      positive-text="确认转移"
      negative-text="取消"
      @positive-click="handleTransferConfirm"
    >
      <n-form ref="transferFormRef" :model="transferFormValue" :rules="transferRules" class="mt-6">
        <p class="mb-4">
          您已选择
          <n-text type="primary" strong>{{ checkedRowKeys.length }}</n-text>
          名党员，请为他们设置新的组织关系。
        </p>
        <n-form-item label="转入目标党支部" path="targetBranchId">
          <n-select
            v-model:value="transferFormValue.targetBranchId"
            placeholder="请选择要转入的党支部"
            :options="targetBranchOptions"
            filterable
          />
        </n-form-item>
        <n-form-item label="在旧党支部的结束日期" path="endDate">
          <n-date-picker
            v-model:formatted-value="transferFormValue.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            class="w-full"
            placeholder="请选择在旧党支部的结束日期"
          />
        </n-form-item>
        <n-form-item label="在新支部的起始日期" path="startDate">
          <n-date-picker
            v-model:formatted-value="transferFormValue.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            class="w-full"
          />
        </n-form-item>
        <n-form-item label="转出原因" path="transferReason">
          <n-input
            v-model:value="transferFormValue.transferReason"
            type="textarea"
            placeholder="请输入转出原因（选填）"
            :rows="2"
          />
        </n-form-item>
      </n-form>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, computed, h, onMounted } from 'vue';
import {
  NDataTable, NButton, NIcon, NCard, NInput, NSpace, NTag,
  NModal, NForm, NFormItem, NSelect, NDatePicker, NText, useMessage
} from 'naive-ui';
import {
  SearchOutline as SearchIcon,
  SwapHorizontalOutline as TransferIcon,
  PersonOutline as PersonIcon
} from '@vicons/ionicons5';
// 引入API接口
import { transferMemberRelations, getBranchList } from '@/api/index.js';
import { generateMemberDataBatch } from '@/utils/memberDataGenerator.js';


const props = defineProps({
  branch: { type: Object, required: true },
  allBranches: { type: Array, default: () => [] }
});
const emit = defineEmits(['data-updated']);

const message = useMessage();

// --- 内部状态 ---
const loading = ref(true);
const memberList = ref([]); // 使用内部 state 存储党员列表
const searchKeyword = ref('');
const checkedRowKeys = ref([]);
const showTransferModal = ref(false);
const transferFormRef = ref(null);
const transferFormValue = ref({
  targetBranchId: null,
  endDate: null,
  startDate: null
});

// --- 新增: 筛选状态 ---
const selectedGender = ref(null);
const selectedStatus = ref(null);
const selectedClass = ref(null);
const selectedGraduationStatus = ref('not_graduated'); // 默认选择未毕业
const selectedDate = ref(null);


// --- 新增: 筛选选项的计算属性 ---
const genderOptions = computed(() =>
  [...new Set(memberList.value.map(m => m.gender))]
    .map(gender => ({ label: gender, value: gender }))
);
const statusOptions = computed(() =>
  [...new Set(memberList.value.map(m => m.politicalStatus))]
    .map(status => ({ label: status, value: status }))
);
const classOptions = computed(() =>
  [...new Set(memberList.value.map(m => m.class))]
    .map(cls => ({ label: cls, value: cls }))
);
const graduationStatusOptions = [
  { label: '已毕业', value: 'graduated' },
  { label: '未毕业', value: 'not_graduated' }
];


// --- 更新: 核心过滤逻辑 ---
const filteredMembers = computed(() => {
  // 从原始列表开始过滤
  let filtered = memberList.value;
  
  // 1. 应用文本搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(member =>
      member.memberName.toLowerCase().includes(keyword) ||
      (member.phoneNumber && member.phoneNumber.includes(keyword))
    );
  }
  
  // 2. 应用性别筛选
  if (selectedGender.value) {
    filtered = filtered.filter(member => member.gender === selectedGender.value);
  }
  
  // 3. 应用政治面貌筛选
  if (selectedStatus.value) {
    filtered = filtered.filter(member => member.politicalStatus === selectedStatus.value);
  }
  
  // 4. 应用班级筛选
  if (selectedClass.value) {
    filtered = filtered.filter(member => member.class === selectedClass.value);
  }
  
  // 5. 应用毕业状态筛选
  if (selectedGraduationStatus.value) {
    filtered = filtered.filter(member => {
      const isGraduated = member.enrollmentStatus === '已毕业' || member.enrollmentStatus === '毕业';
      return selectedGraduationStatus.value === 'graduated' ? isGraduated : !isGraduated;
    });
  }
  
  // 6. 应用日期筛选（特定日期的成员名单）
  if (selectedDate.value) {
    const queryDate = new Date(selectedDate.value);
    filtered = filtered.filter(member => {
      // 检查党员在该日期是否属于该党支部
      if (!member.joinDate) return false;
      
      const joinDate = new Date(member.joinDate);
      const leaveDate = member.leaveDate ? new Date(member.leaveDate) : null;
      
      // 党员必须在查询日期之前或当天加入
      if (joinDate > queryDate) return false;
      
      // 如果有离开日期，必须在查询日期之后或当天离开
      if (leaveDate && leaveDate < queryDate) return false;
      
      return true;
    });
  }

  return filtered;
});

// 检查是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return searchKeyword.value ||
         selectedGender.value ||
         selectedStatus.value ||
         selectedClass.value ||
         selectedGraduationStatus.value !== 'not_graduated' || // 默认值不算激活筛选
         selectedDate.value;
});

// 清除所有筛选条件
const clearAllFilters = () => {
  searchKeyword.value = '';
  selectedGender.value = null;
  selectedStatus.value = null;
  selectedClass.value = null;
  selectedGraduationStatus.value = 'not_graduated'; // 恢复默认值
  selectedDate.value = null;
};

// 检查是否为历史查询
const isHistoricalQuery = computed(() => {
  if (!selectedDate.value) return false;
  
  const queryDate = new Date(selectedDate.value);
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  return queryDate < today;
});

const targetBranchOptions = ref([]);

// 获取所有党支部列表作为转移目标
const fetchBranchListForTransfer = async () => {
  try {
    const result = await getBranchList({ page: 1, pageSize: 100 });
    targetBranchOptions.value = result.list
      .filter(b => b.branchId !== props.branch.branchId)
      .map(b => ({ label: b.branchName, value: b.branchId }));
  } catch (error) {
    console.error('获取党支部列表失败:', error);
  }
};


// --- 更新: 表格列定义 ---
const columns = [
  { type: 'selection' },
  {
    title: '姓名',
    key: 'memberName',
    render: (row) => h('div', { class: 'flex items-center gap-2' }, [
      h(NIcon, { component: PersonIcon }),
      h('span', row.memberName)
    ])
  },
  { title: '性别', key: 'gender', width: 80 },
  { title: '政治面貌', key: 'politicalStatus' },
  { title: '班级', key: 'class' }, // 新增班级列
  { title: '联系电话', key: 'phoneNumber' },
  { title: '入党日期', key: 'joinDate' },
  { title: '学籍状态', key: 'enrollmentStatus' }
];


// --- 工具函数 ---
const formatDate = (dateStr) => {
  if (!dateStr) return '未知日期';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
  } catch (e) {
    return dateStr;
  }
};

// --- 日期筛选功能 ---
const handleDateChange = (value) => {
  selectedDate.value = value;
}

// --- 转移逻辑 ---
const transferRules = {
  targetBranchId: { required: true, message: '必须选择一个目标党支部', trigger: 'change' },
  endDate: { required: true, message: '必须设置在旧党支部的结束日期', trigger: 'change' },
  startDate: { required: true, message: '必须设置在新支部的起始日期', trigger: 'change' }
};

const handleTransferConfirm = async (e) => {
  e.preventDefault();
  try {
    await transferFormRef.value?.validate();
    
    const transferData = {
      memberIds: checkedRowKeys.value,
      fromBranchId: props.branch.branchId,
      toBranchId: transferFormValue.value.targetBranchId,
      transferEndDate: transferFormValue.value.endDate,
      transferStartDate: transferFormValue.value.startDate
    };
    console.log("正在执行党员转移操作，提交数据:", transferData);
    message.loading('正在处理转移请求...', { duration: 1500 });
    
    const result = await transferMemberRelations(transferData);
    
    if (result) {
      message.success('党员组织关系转移成功！');
      
      memberList.value = memberList.value.filter(
        member => !checkedRowKeys.value.includes(member.memberId)
      );

      showTransferModal.value = false;
      checkedRowKeys.value = [];
      transferFormValue.value = { targetBranchId: null, endDate: null, startDate: null };
      
      emit('data-updated');
    } else {
      message.error('转移失败，请重试');
    }

  } catch (errors) {
    console.warn('转移操作失败', errors);
    message.error('转移失败，请重试');
  }
};


// --- 生命周期 ---
onMounted(async () => {
  loading.value = true;
  console.log("MemberManagement.vue: 正在为 Demo 生成内部模拟数据...");
  
  // 生成更多数据以便于筛选演示，确保数据生成器包含 `class` 字段
  memberList.value = generateMemberDataBatch(40);
  
  // 获取党支部列表用于转移功能
  await fetchBranchListForTransfer();
  
  loading.value = false;
  console.log("模拟数据生成完毕!");
});
</script>

<style scoped>
.date-query-card {
  background-color: #e6f7ff;
  border-left: 4px solid #1890ff;
}
</style>